

package org.privat24.api;

import org.privat24.api.misc.TransferUtil;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import org.privat24.api.misc.SignatureUtil;


public class Privat24API {

    private final TransferUtil transferService = new TransferUtil();
    
    private final String merchantId;
    private final String password;
    private final String url;

    public Privat24API(String merchantId, String password, String url) {
        this.merchantId = merchantId;
        this.password = password;
        this.url = url;
    }
        
    public String sendPrpRequest() throws IOException { // отправка запроса prp, возвращает xml-ответ
	String dataField = "<data><oper>prp</oper></data>";
        String merchantField = buildMerchantField(dataField);
        String request = buildRequest(merchantField, dataField);
	return this.sendRequest(request);
    } 
   
    /*
    * отправка запроса 
    * payments - коллекция платежей
    * wait - время задержки платежа в секундах
    * isTest - тестовый ли платёж
    */
    public String sendCmtRequest(List<Payment> payments, int secondsToWait, boolean isTestRequest) throws UnsupportedEncodingException, IOException  {
        String dataField     = buildDataField(payments, secondsToWait, isTestRequest);
        String merchantField = buildMerchantField(dataField);
        String request       = buildRequest(merchantField, dataField);
        //System.err.println(request);
        return this.sendRequest(request);  
    }

    private String sendRequest(String data) throws IOException {
        return transferService.getResponseXML(data, url);
    }

    private String buildDataField(List<Payment> payments, int secondsToWait, boolean testRequest) throws UnsupportedEncodingException {
        StringBuilder builder = new StringBuilder();
        builder.append("<data>");
        builder.append("<oper>cmt</oper>");
        builder.append("<wait>").append(secondsToWait).append("</wait>");
        builder.append("<test>").append(testRequest ? 1 : 0).append("</test>");
        for(Payment payment : payments) {
                builder.append("<payment id=\"").append(payment.getId()).append("\">");
                // builder.append("<props>");
                for (Object key : payment.getKeys()) {
                    if (key.equals("id") || key.equals("debet") || key.equals("credit") || payment.get(key)==null){
                        continue;
                    }

                    builder.append("<prop name=\"").append(key).append("\" value=\"").append(URLEncoder.encode((String)payment.get(key), "UTF-8")).append("\" />");
                }
                // builder.append("</props>");
                builder.append("</payment>");
        }
        builder.append("</data>");
        String result = builder.toString();
        result = result.replaceAll("%2B","+");
        return result;
    }

    private String buildMerchantField(String dataField) {
        dataField = dataField.replace("<data>", "").replace("</data>", "");
        String signature =  SignatureUtil.calculateSignature(password, dataField);
        StringBuilder builder = new StringBuilder();
        builder.append("<merchant>");
        builder.append("<id>").append(merchantId).append("</id>");
        builder.append("<signature>").append(signature).append("</signature>");
        builder.append("</merchant>");
        return builder.toString();
    }

    private String buildRequest(String merchantField, String dataField) {
        StringBuilder builder = new StringBuilder();
        builder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        builder.append("<request version=\"1.0\">");
        builder.append(merchantField);
        builder.append(dataField);
        builder.append("</request>");
        return builder.toString();
    }
    
    
}
